﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using BLToolkit.DataAccess;
using BLToolkit.Mapping;
using Mc.Fe.Entities;

namespace Mc.Fe.Data
{
    public abstract class DataAccesor : AccessorBase<DataAccesor>
    {
        [SqlQuery(@"SELECT * FROM FAC04_FECONTROL WHERE FAC04ESTADO = 'P' ORDER BY FAC04CODEMP ASC, FAC01COD ASC, FAC04NUMDOC ASC")]
        public abstract List<Documento> BuscarDocumentos();

        [SqlQuery(@"SELECT * 
                    FROM FAC04_CABFACTURA T1
                    WHERE T1.FAC04ESTADODOC = @estado AND T1.FAC04FECHA >= @fechaDesde
                    AND T1.FAC04NUMDOC = '003-0003124'
                    AND T1.FAC04NUMDOC NOT IN(SELECT T2.FAC04NUMDOC FROM FAC04_FECONTROL T2)
                    ORDER BY T1.FAC04CODEMP ASC, T1.FAC01COD ASC, T1.FAC04NUMDOC ASC")]
        public abstract List<Factura> BuscarFacturasPendientes(string @estado, string @fechaDesde);

        [SqlQuery(@"SELECT * FROM FAC04_CABFACTURA WHERE FAC04CODEMP = @codigoEmpresa AND FAC01COD = @codigoTipoDocumento AND FAC04NUMDOC = @nroDocumento")]
        public abstract Factura BuscarFactura(string @codigoEmpresa, string @codigoTipoDocumento, string @nroDocumento);

        [SqlQuery(@"SELECT * FROM FAC05_DETFACTURA WHERE FAC05CODEMP = @codigoEmpresa AND FAC01COD = @codigoTipoDocumento AND FAC04NUMDOC = @nroDocumento ORDER BY FAC05CODFACDET ASC")]
        public abstract List<DetalleFactura> BuscarDetalleFacturas(string @codigoEmpresa, string @codigoTipoDocumento, string @nroDocumento);

        [SqlQuery(@"UPDATE FAC04_FECONTROL SET FAC04ESTADO =  @Estado, FAC04FECRESP = GETDATE() WHERE FAC04REFERENCIAID = @referenciaId")]
        public abstract void ActualizarEstado(string @referenciaId, string @Estado);

        public int GenerarCorrelativo()
        {
            int retono = 0;
            var dm = this.CreateDbManager();

            retono = Convert.ToInt32(dm.SetCommand(@"SELECT ISNULL(MAX(FAC04ITEM), 0) + 1 FROM FAC04_FENOTIFICACION").ExecuteScalar());

            return retono;
        }

        /// <summary>
        /// Guarda tabla de control
        /// </summary>
        /// <param name="documento"></param>
        public void GuardarControl(Documento documento)
        {
            SqlQuery<Documento> query = new SqlQuery<Documento>();
            query.Insert(documento);
        }

        /// <summary>
        /// Guarda tabla de notificaciones
        /// </summary>
        /// <param name="notificacion"></param>
        public void GuardarNotificacion(Notificacion notificacion)
        {
            SqlQuery<Notificacion> query = new SqlQuery<Notificacion>();
            query.Insert(notificacion);
        }
    }
}
